package com.ruoyi.netty.server;

import com.ruoyi.netty.config.NettyConfig;
import com.ruoyi.netty.connection.ConnectionManager;
import com.ruoyi.netty.handler.ModbusServerHandler;
import com.ruoyi.netty.protocol.ModbusDecoder;
import com.ruoyi.netty.protocol.ModbusEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
 * Netty服务器，支持Modbus TCP协议
 */
@Component
@Slf4j
public class NettyServer {
    
    @Value("${netty.port:8888}")
    private int port;
    
    @Value("${netty.boss-threads:1}")
    private int bossThreads;
    
    @Value("${netty.worker-threads:4}")
    private int workerThreads;
    
    @Value("${netty.keep-alive:true}")
    private boolean keepAlive;
    
    @Value("${netty.timeout:180}")
    private int timeout;
    
    @Autowired
    private NettyConfig nettyConfig;
    
    @Autowired
    private ModbusServerHandler modbusServerHandler;
    
    @Autowired
    private ConnectionManager connectionManager;
    
    @Autowired(required = false)
    private SslContext sslContext;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture channelFuture;
    
    /**
     * 启动Netty服务器
     */
    @PostConstruct
    public void start() {
        new Thread(() -> {
            try {
                bossGroup = new NioEventLoopGroup(bossThreads);
                workerGroup = new NioEventLoopGroup(workerThreads);
                
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) {
                                ch.pipeline().addLast(
                                        // 空闲检测
                                        new IdleStateHandler(timeout, 0, 0, TimeUnit.SECONDS),
                                        // 使用现有的ModbusDecoder和ModbusEncoder
                                        new ModbusDecoder(),
                                        new ModbusEncoder(),
                                        // 业务处理
                                        modbusServerHandler
                                );
                            }
                        })
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .childOption(ChannelOption.SO_KEEPALIVE, keepAlive);
                
                // 绑定端口并启动
                channelFuture = bootstrap.bind(port).sync();
                log.info("Modbus TCP Server started at port {}", port);
                
                // 等待服务器关闭
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                log.error("Netty server error: {}", e.getMessage(), e);
            } finally {
                shutdown();
            }
        }, "netty-server-thread").start();
    }
    
    /**
     * 关闭Netty服务器
     */
    @PreDestroy
    public void shutdown() {
        if (channelFuture != null) {
            channelFuture.channel().close();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        log.info("Netty server shutdown");
    }
} 